package org.example;

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.zookeeper.Testable;

import java.util.Comparator;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.HashMap;



public class Task1Driver1 {
    public static class Task1Mapper1 extends Mapper<Object,Text,Text,Text>{
        private Text date = new Text();
        private IntWritable purchase = new IntWritable();
        private IntWritable redeem = new IntWritable();

        @Override
        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            String[] parts = value.toString().split(",");
            if(parts.length>=3){
                date.set(parts[0]); // 第一列是日期
                purchase.set(Integer.parseInt(parts[1])); // 第二列是购买金额
                redeem.set(Integer.parseInt(parts[2])); // 第三列是赎回金额
                String result=purchase.toString()+","+redeem.toString(); //以逗号分隔购买额和赎回额
                Text capital=new Text(result);
                context.write(date, capital);
            }
        }
    }

    public static class Task1Reducer1 extends Reducer<Text,Text,Text,Text>{
        @Override
        public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            int sumPurchase = 0;
            int sumRedeem = 0;
            for (Text val : values) {
                String[] tmpval=val.toString().split(",");
                int purchase = Integer.parseInt(tmpval[0]);
                int redeem = Integer.parseInt(tmpval[1]);
                sumPurchase += purchase;
                sumRedeem += redeem;
            }
            String result=String.valueOf(sumPurchase)+","+String.valueOf(sumRedeem);
            Text textResult=new Text(result);
            context.write(key, textResult);
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "task1 amounts/day");

        job.setJarByClass(Task1Driver1.class);
        job.setMapperClass(Task1Mapper1.class);
        job.setReducerClass(Task1Reducer1.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }

}
